package spill;

import java.awt.Color;

import java.awt.*;

public class Screen extends Panel {
	
	private static final long serialVersionUID = -6105846670652730405L;
	private int bufferWidth;
	private int bufferHeight;
	private Image bufferImage;
	private Graphics bufferGraphics;
	private Engine eng;
	
	public Screen() {
		super();
		this.setBackground(Color.white);
		this.setBounds(0, 0, 700, 500);
		this.setVisible(true);
	}
	public void setEngine(Engine eng) {
		this.eng = eng;
	}
	public void update(Graphics g) {
		paint(g);
	}
	public void paint(Graphics g) {
		if (bufferWidth!=getSize().width || bufferHeight!=getSize().height ||
				bufferImage==null || bufferGraphics==null) {
			resetBuffer();
		}
		if (bufferGraphics!=null) {
			bufferGraphics.clearRect(0, 0, bufferWidth, bufferHeight);
			paintBuffer(bufferGraphics);
			g.drawImage(bufferImage, 0, 0, this);
		}
	}
	private void resetBuffer() {
		bufferWidth = getSize().width;
		bufferHeight = getSize().height;
		if (bufferGraphics != null) {
			bufferGraphics.dispose();
			bufferGraphics=null;
		}
		if (bufferImage != null) {
			bufferImage.flush();
			bufferImage=null;
		}
		System.gc();
		
		bufferImage=createImage(bufferWidth, bufferHeight);
		bufferGraphics=bufferImage.getGraphics();
	}
	public void paintBuffer(Graphics g) {
		if (eng != null) {
			eng.drawItems(g);
		}
	}
}
